import './data_table.html';

import './record.js';

import '../pagination/pagination.js';



Template.data_table.onCreated(function () {

		let self = this;
		self.page = new ReactiveVar();
		self.counter = new ReactiveVar(0);
		self.pagesize = new ReactiveVar(3);
		self.records = new ReactiveVar();
		self.loadready = new ReactiveVar();
		self.all_checked = new ReactiveVar(false);
		self.checked_counter = new ReactiveVar(0);
		let checked_ids = new Array();
		self.checked_ids = new ReactiveVar(checked_ids);
		self.deleteSuccess = new ReactiveVar(false);
		self.deletedCounter = new ReactiveVar(0);
		
		Meteor.subscribe(this.data.subsReady, parseInt(FlowRouter.getParam("page"))-1, 3);
	
		self.autorun((c) => {

		self.loadready.set(FlowRouter.subsReady(this.data.subsReady));

		if (self.loadready.get()) {
			self.checked_ids.set(new Array());
			self.all_checked.set(false);
			let pagesize = self.pagesize.get();
			self.page.set(FlowRouter.current().params.page-1);
			
			let data = this.data.model.find({}, {skip: self.page.get()*pagesize, limit: pagesize, sort: {createdAt: -1}});
			Meteor.subscribe(this.data.subsReady, self.page.get(), pagesize);
			self.counter.set(data.count());
			self.records.set(data);

			self.checked_counter.set(0);

			UIBlock.unblock();


		}else{
			self.loadready.set(FlowRouter.subsReady(this.data.subsReady));
		    // FlowRouter.go('/admin/roles/1');
			UIBlock.block('正在载入');
			

		}

		if (self.deleteSuccess.get()) {
				FlashMessages.clear();
				self.deleteSuccess.set(false);
				FlashMessages.sendSuccess("成功删除"+self.deletedCounter.get()+"条记录");
				self.deletedCounter.set(0);

			}



	  });
	

});

Template.data_table.onRendered(function () {
	
	
	$('.delete-checked').hide();
	$('.ban-checked').hide();

});

Template.data_table.helpers({
	records() {

		let isReady = Template.instance().loadready.get();

		let data = Template.instance().records.get();

		if (!isReady) {
			return ["载入中"]
		}	
		
			
    	return data;
	},

  	canCreate(modelname){
  		if (modelname == "用户") {
  			return false;
  		}
  		return true;
  	},


  	subsReadyName(){
  		return this.data.subsReady;
  	},

	  isVisible(record){
	  	
	  		if (record.hasOwnProperty('username')) {
	  			if (record.username == 'admin') {
	  				return false;
	  			}
	  			if (record.username == Meteor.user().username) {
	  				return false;
	  			}
	  		}
	  	return true;
	  },

	isEmpty(){
		let isReady = Template.instance().loadready.get();
		if (isReady) {
			if (Template.instance().counter.get() === 0) {
				return true;
			}
			return false;
		}

		return false;
	},
	 //以下都是分页器的方法pagation methods

	  pageNumber(offset=0) {
			let isReady = Template.instance().loadready.get();
			if (isReady) {
				return Template.instance().page.get()+1+parseInt(offset);
			}
			return '...';

	  }
   
});

Template.data_table.events({
	  
		'submit .role-edit'(event) {
	    event.preventDefault();

	    const target = event.target;
	    const name = target.getElementsByTagName("input")[0];
			const weight = target.getElementsByTagName("input")[1];
			const id = target.getElementsByTagName("input")[2];
	    Meteor.call('roles.update', id.value, name.value, weight.value, (error) => {
	      if (error) {
	        alert(error.error);
	      } else {

	        $('#edit-role-modal').modal('hide');
			FlashMessages.sendSuccess("更新成功");
	      }
	    });

	  },
	'ifChecked .check-one'(event, instance) {
		
		event.preventDefault();
		event.stopPropagation();
		$('.delete-checked').show();
		$('.ban-checked').show();
		let check_counter = instance.checked_counter.get();
		check_counter++;
		instance.checked_counter.set(check_counter);
		let checked_ids = instance.checked_ids.get();
		
		checked_ids.push(this.record._id);
		instance.checked_ids.set(checked_ids);
		if (check_counter === instance.counter.get()) {
			instance.all_checked.set(true);
			$(".check-all").iCheck('check');

		}
		


	},
	'ifUnchecked .check-one'(event, instance) {
		
		event.preventDefault();
		event.stopPropagation();
		instance.all_checked.set(false);

		$(".check-all").iCheck('uncheck');
		let check_counter = instance.checked_counter.get();
		check_counter--;
		instance.checked_counter.set(check_counter);

		let checked_ids = instance.checked_ids.get();

		if (check_counter === 0 ) {
			$('.delete-checked').hide();
			$('.ban-checked').hide();
			checked_ids = new Array();
			instance.checked_ids.set(checked_ids);
		}else{

			for (var i = 0; i < checked_ids.length; i++) {
				if (checked_ids[i] === this.record._id) {
					checked_ids.splice(i,1);

				}
			}
			instance.checked_ids.set(checked_ids);
		}
			


	},
	'ifClicked .check-all'(event, instance) {
		
		event.preventDefault();
		event.stopPropagation();
		if (instance.all_checked.get()) {
			$(".check-all").iCheck('uncheck');
			$(".check-one").iCheck('uncheck');
			instance.all_checked.set(false);
			

		}else{
			$(".check-all").iCheck('check');
			$(".check-one").iCheck('check');
			instance.all_checked.set(true);
			
		}
	},
	'click .delete-checked'(event, instance) {
		event.preventDefault();
		event.stopPropagation();
		instance.deleteSuccess.set(false);
		let records_size = instance.checked_ids.get().length;
		if (records_size === 0) {
			alert('请先勾选!');
			instance.deleteSuccess.set(false);
			return false;
		}


		
		if (confirm("是否确认删除所勾选的"+records_size+"条记录?")) {
			UIBlock.block('正在删除');
			for (var i = 0; i < instance.checked_ids.get().length; i++) {
				Meteor.call(this.modelmethods.delete, instance.checked_ids.get()[i], (error) => {
						if (error) {
							alert(error);
							isSuccess = true;
							$(".check-all").iCheck('uncheck');
							$(".check-one").iCheck('uncheck');
						} else {
							UIBlock.unblock();
							instance.deleteSuccess.set(true);
							instance.deletedCounter.set(records_size);
							$(".check-all").iCheck('uncheck');
							$(".check-one").iCheck('uncheck');

						}
					});

			}

		}
		

	},

	'click .ban-checked'(event, instance) {
		event.preventDefault();
		event.stopPropagation();
		instance.deleteSuccess.set(false);
		let records_size = instance.checked_ids.get().length;
		if (records_size === 0) {
			alert('请先勾选!');
			instance.deleteSuccess.set(false);
			return false;
		}
		
		if (confirm("是否确认禁用所勾选的"+records_size+"个用户?")) {
			UIBlock.block('正在禁用');
			for (var i = 0; i < instance.checked_ids.get().length; i++) {
				Meteor.call('users.block', instance.checked_ids.get()[i], true, (error) => {
						if (error) {
							alert(error);
							isSuccess = true;
							$(".check-all").iCheck('uncheck');
							$(".check-one").iCheck('uncheck');
							$('.ban-checked').hide();
						} else {
							UIBlock.unblock();
							$(".toggle.btn").addClass("off");
							$('.ban-checked').hide();
							instance.deleteSuccess.set(true);
							instance.deletedCounter.set(records_size);
							$(".check-all").iCheck('uncheck');
							$(".check-one").iCheck('uncheck');

						}
					});

			}

		}
	}


});
